const App = {
    el: '#app',
    data() {
        return {
            photo,
            form: {
                Article_Name: '',
                Article_Exchange_SerialNumber: '',
                SQLSerialNumber: 't_article_info2',
                PaginationNumber: 1, //页码
                RowAmount: 10,
                Condition: window.btoa(unescape(encodeURIComponent("%%,%")))
            },
            tableData: [],
            total: 0,
            searchQuery: '',//身份证号
            address: [],//兑换点
            multipleSelection: [],
            account: {},
            showDialog: false,
            loading: false,
            relativePath: '',
        }

    },
    mounted() {
        let currentURL = window.location.href;
        currentURL = currentURL.replace(/([?&])ACCESSTOKEN=[^&]*(&|$)/, '$1').replace(/[?&]$/, '')
        this.relativePath = currentURL.substring(
            currentURL.lastIndexOf("view"),
            currentURL.length
        );
        this.getAddress();
    },
    computed: {
        selectArticle() {
            let Quantity = 0, Party_Point = 0, Villager_Point = 0;
            this.multipleSelection.forEach(item => {
                Quantity += item.Quantity;
                if (item.Points_Type == '0') {
                    Villager_Point = accAdd(accMul(item.Villager_Point, item.Quantity), Villager_Point);
                } else if (item.Points_Type == '1') {
                    Party_Point = accAdd(accMul(item.Party_Point, item.Quantity), Party_Point);
                }
            })
            return { Quantity, Party_Point, Villager_Point };
        },
        remainPoints() {
            const { Party_Remain_Points, Villager_Remain_Points } = this.account;
            const { Party_Point, Villager_Point } = this.selectArticle;

            let New_Party_Remain_Points = '', New_Villager_Remain_Points = '';
            if (Party_Point <= Party_Remain_Points) {
                New_Party_Remain_Points = accSub(Party_Remain_Points, Party_Point);
            } else if (Party_Point > Party_Remain_Points) {
                New_Party_Remain_Points = '积分不足'
            }

            if (Villager_Point <= Villager_Remain_Points) {
                New_Villager_Remain_Points = accSub(Villager_Remain_Points, Villager_Point);
            } else if (Villager_Point > Villager_Remain_Points) {
                New_Villager_Remain_Points = '积分不足'
            }

            return { New_Party_Remain_Points, New_Villager_Remain_Points }
        }
    },
    methods: {
        Query() {
            this.form.Condition = window.btoa(unescape(encodeURIComponent("%" + this.form.Article_Name + "%," + this.form.Article_Exchange_SerialNumber)));
            this.getList(this.form);
        },
        getAddress() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'article_exchange_address',
                    Condition: `Row_Status='0' AND VillageNumber IN (${getCookie('village')})`,
                },
                success: (res) => {
                    if (res.length > 0) {
                        this.form.Article_Exchange_SerialNumber = res[0].Article_Exchange_SerialNumber
                    } else {
                        this.$message({
                            message: '暂无兑换点',
                            type: 'warning'
                        })
                    }
                    this.address = res;
                    this.form.Condition = window.btoa(unescape(encodeURIComponent("%" + this.form.Article_Name + "%," + this.form.Article_Exchange_SerialNumber)));
                    this.getList(this.form);
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        getList(data) {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                method: "post",
                data,
                success: (res) => {
                    this.total = res.TotalRows;//总数量
                    res.Rows.forEach(item => {
                        item.Quantity = 1;
                        if (item.Party_Point >= 0 && item.Villager_Point >= 0) {
                            item.Points_Type = '0';
                            item.disabled = false;
                        } else if (item.Party_Point >= 0) {
                            item.Points_Type = '1';
                            item.disabled = true;
                        } else if (item.Villager_Point) {
                            item.Points_Type = '0';
                            item.disabled = true;
                        }
                    })
                    this.tableData = res.Rows;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleCurrentChange(newPage) {
            this.form.PaginationNumber = newPage;
            this.getList(this.form);
        },
        handleSizeChange(newSize) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = newSize;
            this.getList(this.form);
        },
        InputPersonal(val) {
            if (val) {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                    method: "post",
                    data: {
                        SQLSerialNumber: 'f_personal_points_account',
                        Condition: window.btoa(unescape(encodeURIComponent(val))),
                        ExtensionCondition: ''
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            this.account = res[0];
                        } else {
                            this.account = {}
                        }
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest)
                    }
                })
            } else {
                this.account = {}
            }
        },
        showSalesOrder() {
            const { New_Party_Remain_Points, New_Villager_Remain_Points } = this.remainPoints;
            if (this.multipleSelection.length == 0) {
                this.$message({
                    message: '暂无结算商品！',
                    type: 'warning'
                });
            } else if (!this.account.Personal_Name) {
                this.$message({
                    message: '未查询到用户积分账户，无法结算！',
                    type: 'warning'
                });
            } else if (!isNaN(New_Party_Remain_Points) && !isNaN(New_Villager_Remain_Points)) {
                this.showDialog = true;
            } else {
                this.$message({
                    message: '积分不足，无法结算！',
                    type: 'warning'
                });
            }
        },
        handleSubmit() {
            this.loading = true;
            let Article_Inventory_SerialNumber = this.multipleSelection.map(i => "'" + i.Article_Inventory_SerialNumber + "'").join(',');
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                method: "post",
                data: {
                    Data: JSON.stringify([{
                        tableName: 'article_inventory',
                        Condition: window.btoa(unescape(encodeURIComponent("Article_Inventory_SerialNumber IN (" + Article_Inventory_SerialNumber + ")"))),
                    }, {
                        tableName: 'personal_points_account',
                        Condition: window.btoa(unescape(encodeURIComponent("ID_Card_Number='" + this.account.ID_Card_Number + "'"))),
                    }]),
                },
                success: ({ article_inventory, personal_points_account }) => {
                    const ls_Datetime = getYMDHMSDate();
                    let sales_order_detail = [], article_inventory_out = [], personal_points_change_log = [];
                    //生成销售订单明细和出库单
                    this.multipleSelection.forEach(item => {
                        sales_order_detail.push({
                            Article_Inventory_SerialNumber: item.Article_Inventory_SerialNumber,
                            Article_SerialNumber: item.Article_SerialNumber,
                            Specifications_SerialNumber: item.Specifications_SerialNumber,
                            Quantity: item.Quantity,
                            Unit_Points: item.Points_Type == '0' ? item.Villager_Point : item.Party_Point,
                            Points_Type: item.Points_Type,
                            Sales_Points: accMul((item.Points_Type == '0' ? item.Villager_Point : item.Party_Point), item.Quantity)
                        })
                        article_inventory_out.push({
                            Article_Inventory_SerialNumber: item.Article_Inventory_SerialNumber,
                            Article_SerialNumber: item.Article_SerialNumber,
                            Specifications_SerialNumber: item.Specifications_SerialNumber,
                            Inventory_Out_Datetime: ls_Datetime,
                            Children: {
                                article_inventory_out_detail: [{
                                    Article_Purpose: '商品被兑换',
                                    Inventory_Out_Quantity: item.Quantity
                                }]
                            }
                        })
                    })
                    //回写积分账户
                    personal_points_account.forEach(item => {
                        if (item.Points_Type == '0') {
                            item.Remain_Points = accSub(item.Remain_Points, this.selectArticle.Villager_Point);
                            item.Sales_Points = accAdd(item.Sales_Points, this.selectArticle.Villager_Point);
                        } else if (item.Points_Type == '1') {
                            item.Remain_Points = accSub(item.Remain_Points, this.selectArticle.Party_Point);
                            item.Sales_Points = accAdd(item.Sales_Points, this.selectArticle.Party_Point);
                        }
                    });
                    //生成日志
                    if (this.selectArticle.Villager_Point > 0) {
                        personal_points_change_log.push({
                            ID_Card_Number: this.account.ID_Card_Number,
                            Points_Title: '兑换商品扣减村民积分',
                            Points_Type: '0',
                            Change_Points: '-' + this.selectArticle.Villager_Point,
                            Remain_Points: this.remainPoints.New_Villager_Remain_Points,
                            Notes: '兑换商品扣减村民积分'
                        })
                    }
                    if (this.selectArticle.Party_Point > 0) {
                        personal_points_change_log.push({
                            ID_Card_Number: this.account.ID_Card_Number,
                            Points_Title: '兑换商品扣减党员积分',
                            Points_Type: '1',
                            Change_Points: '-' + this.selectArticle.Party_Point,
                            Remain_Points: this.remainPoints.New_Party_Remain_Points,
                            Notes: '兑换商品扣减党员积分'
                        })
                    }
                    //回写商品库存
                    article_inventory.forEach(item => {
                        let obj = this.multipleSelection.filter(i => i.Article_Inventory_SerialNumber == item.Article_Inventory_SerialNumber)[0];
                        item.Inventory_Quantity = accSub(item.Inventory_Quantity, obj.Quantity);
                        item.Inventory_Out_Quantity = accAdd(item.Inventory_Out_Quantity, obj.Quantity);
                    })
                    let lJSONObject_DataSet = {
                        Add: {
                            sales_order: [{//销售订单
                                ID_Card_Number: this.account.ID_Card_Number,
                                Sales_Datetime: ls_Datetime,
                                Sales_Villager_Point: this.selectArticle.Villager_Point,
                                Sales_Party_Point: this.selectArticle.Party_Point,
                                Children: {
                                    sales_order_detail
                                }
                            }],
                            article_inventory_out,//出库单
                            personal_points_change_log,//日志
                        },
                        Modify: {
                            personal_points_account,//回写积分账户
                            article_inventory,//回写库存
                        }
                    };
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            this.getList(this.form);
                            this.showDialog = false;
                            this.account = {};
                            this.searchQuery = '';
                            this.$message({
                                message: '结算成功',
                                type: 'success'
                            });
                        }
                        this.loading = false;
                    })
                    // $.ajax({
                    //     headers: requestHeaders("JSON"),
                    //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                    //     method: "post",
                    //     data: JSON.stringify({
                    //         Data: lJSONObject_DataSet,
                    //     }),
                    //     success: (res) => {
                    //         if (res.Status == 'success') {
                    //             this.getList(this.form);
                    //             this.showDialog = false;
                    //             this.account = {};
                    //             this.searchQuery = '';
                    //             this.$message({
                    //                 message: '结算成功',
                    //                 type: 'success'
                    //             });
                    //         }
                    //     },
                    //     complete: (XMLHttpRequest) => {
                    //         this.loading = false;
                    //         requestPretreatment(XMLHttpRequest)
                    //     }
                    // });
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                }
            })
        }
    }
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
